<template>
  <!-- 店铺协议添加修改页面 -->
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? '新增' : '编辑'" :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-position="top" label-width="120px">
      <el-form-item prop="type" label="协议类型">
        <ren-radio-group v-model="dataForm.type" dict-type="agreement_type"></ren-radio-group>
      </el-form-item>
      <el-form-item prop="content" label="协议内容" v-loading="loading" v-if="visible">
        <div style="border: 1px solid #ccc;">
          <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
          />
          <Editor
              style="height: 500px; overflow-y: hidden;"
              v-model="dataForm.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
          />
        </div>

      </el-form-item>
    </el-form>

    <template slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确认</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import Cookies from "js-cookie";
import axios from "axios";
import { Base64 } from 'js-base64';
import * as imageConversion from "image-conversion";
import {Message, Notification} from "element-ui";

export default {
  components: { Editor, Toolbar },
  data() {
    return {
      visible: false,
      loading: false,
      dialogVisible: false,
      dataForm: {
        id: '',                          //id
        type:'',                         //0服务协议1隐私协议
        content:'',                      //协议内容
      },
      editor: null,
      toolbarConfig: {
        excludeKeys: [],//屏蔽图片链接上传，视频上传
      },
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          // 上传图片配置
          uploadImage: {
            customUpload: this.uploadImage // 自定义上传方法
          },
          // 上传视频配置
          uploadVideo: {
            customUpload: this.uploadVideo // 自定义上传方法
          },
        }
      },
      mode: 'default', // or 'simple'
    }
  },
  computed: {
    dataRule() {
      return {
        type: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        content: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ]
      }
    }
  },
  mounted() {
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    init() {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 获取信息
    getInfo() {
      this.$http.get(`/api/shopProtocol/${this.dataForm.id}`).then(({data: res}) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
      }).catch(() => {
      })
    },
    //上传图片
    async uploadImage (file, insertFn) {
      const form = new FormData()
      this.loading = true
      const blobFile = await imageConversion.compressAccurately(file, {size:`${window.SITE_CONFIG['imageConversionQuality']}`,type:'image/png'})// 设置压缩大小默认700k
      const resFile = new File([blobFile], file.name, {type: blobFile.type})// blob转file对象
      form.append('file', resFile)
      // 发送post请求
      const instance = axios.create({
        baseURL: `${window.SITE_CONFIG['apiURL']}`,
        timeout: `${window.SITE_CONFIG['uploadTimeout']}`,
        headers: {
          'token': Cookies.get('token'),//接口需要的token
          'Content-Type': 'application/json'
        }
      })
      instance.post(`/sys/oss/upload?token=${Cookies.get('token')}`, form
      ).then(res => {
        Notification.success({
          title: '成功',
          message: res.data.msg||'上传成功！',
          type: 'success'
        })
        this.loading = false
        let {data} = res.data
        insertFn(data.src)
      }).catch(err => {
        this.loading = false
        console.log(err)
        Message.error(err.data.msg||'上传失败')
      })
    },
    //上传视频
    async uploadVideo(file, insertFn) {
      const { type } = file
      if(type.indexOf("video") < 0) {
        Message.warning("请选择上传视频!")
        return false
      }
      if(file.size > `${window.SITE_CONFIG['uploadVideoMaxSize']}`* 1024 * 1024) {
        Message.warning(`视频大小不能超过${window.SITE_CONFIG['uploadVideoMaxSize']}M!`)
        return false
      }
      const form = new FormData()
      form.append("file", file)
      // 发送post请求
      this.loading = true
      const instance = axios.create({
        baseURL: `${window.SITE_CONFIG['apiURL']}`,
        timeout: `${window.SITE_CONFIG['uploadTimeout']}`,
        headers: {
          'token': Cookies.get('token'),//接口需要的token
          'Content-Type': 'application/json'
        }
      })
      instance.post(`/sys/oss/upload?token=${Cookies.get('token')}`, form
      ).then(res => {
        Notification.success({
          title: '成功',
          message: res.data.msg||'上传成功！',
          type: 'success'
        })
        this.loading = false
        let {data} = res.data
        insertFn(data.src)
      }).catch(err => {
        this.loading = false
        console.log(err)
        Message.error(err.data.msg)
      })
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        const item = {...this.dataForm}
        item.content = Base64.encode(item.content)
        this.$http[!this.dataForm.id ? 'post' : 'put']('/api/shopProtocol', item).then(({data: res}) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch((error) => {
          //console.log(error)
        })
      })
    }, 1000, {'leading': true, 'trailing': false}),
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      !this.dataForm.id? this.editor.clear():''
    },

  }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css">

</style>
